<template>
  <div class="app-container">
    <el-divider>随机分组</el-divider>
    <el-card style="margin-bottom: 30px">
      <div style="display: flex; align-items: center" slot="header">
        <span>选手名单</span>
        <div style="display: flex; margin-left: auto; align-items: center">
          <el-button
            size="mini"
            v-if="!isAdd"
            @click="isAdd = true"
            type="primary"
            >添加选手</el-button
          >
          <div style="display: flex; align-items: center" v-else>
            <el-input
              style="margin-left: 10px"
              size="small"
              width="30"
              placeholder="输入名字"
              v-model="newName"
              @change="addNameChange"
              clearable
            ></el-input>
            <el-button
              @click="newName ? addNameChange : (isAdd = false)"
              style="margin-left: 5px"
              type="primary"
              size="mini"
              >{{ newName ? "确定" : "取消" }}</el-button
            >
          </div>
        </div>
        <el-divider direction="vertical"></el-divider>
        <el-button size="mini" @click="startShuffle" type="primary"
          >点击分组</el-button
        >
      </div>
      <el-checkbox
        :indeterminate="isIndeterminate"
        v-model="checkAll"
        @change="handleCheckAllChange"
        border
        >全选</el-checkbox
      >
      <el-checkbox-group v-model="checkList">
        <el-checkbox
          v-for="item in nameList"
          :key="item"
          :label="item"
          border
          @change="nameChange"
        >
          <div class="check-box">
            <span
              style="
                display: grid;
                justify-content: space-between;
                grid-template-columns: repeat(auto-fill, 50px);
                grid-gap: 16px;
                text-align-last: justify;
                overflow: auto;
              "
              >{{ item }}</span
            >
            <el-button
              @click="deleteName(item)"
              class="delete-button"
              type="text"
              >删除</el-button
            >
          </div>
        </el-checkbox>
      </el-checkbox-group>
    </el-card>
    <div class="app-container_card">
      <el-card class="box-card">
        <template #header>
          <span>随机分组左</span>
        </template>
        <div class="card-content">
          <div v-for="o in nameGroupOne" :key="o" class="text_item">
            {{ o }}
          </div>
        </div>
      </el-card>
      <el-card class="box-card">
        <template #header>
          <span>随机分组右</span>
        </template>
        <div class="card-content">
          <div v-for="o in nameGroupTwo" :key="o" class="text_item">
            {{ o }}
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { shuffle, showMessage, validateName } from "./index.js/index.js";
export default {
  data() {
    return {
      checkList: [],
      selectPlayer: [],
      nameGroupOne: [],
      nameGroupTwo: [],
      // 全选
      checkAll: false,
      isIndeterminate: true,
      // 新名字
      newName: "",
      // 添加
      isAdd: false,
    };
  },
  created() {
    this.$store.dispatch("user/loadNames"); // 组件创建时加载名字列表
  },
  computed: {
    ...mapState("user", ["nameList"]), // 将 Vuex 中的 nameList 映射到组件的计算属性中
  },
  methods: {
    // 清空分组
    clearGroups() {
      this.nameGroupOne = [];
      this.nameGroupTwo = [];
    },
    // 选定选手
    nameChange() {
      // 过滤出选中的名字
      const selectedNames = this.nameList.filter((name) =>
        this.checkList.includes(name)
      );
      // 计算选中的名字数量
      const selectedCount = selectedNames.length;
      // 更新全选和部分选中状态
      this.checkAll = selectedCount === this.nameList.length;
      this.isIndeterminate =
        selectedCount > 0 && selectedCount < this.nameList.length;
      // 返回选中的名字列表
      return selectedNames;
    },
    // 全选操作
    handleCheckAllChange(isAll) {
      // 根据是否全选来设置 checkList
      this.checkList = isAll ? this.nameList : [];
      // 如果不是全选，则清空分组
      if (!isAll) {
        this.clearGroups();
      }
      // 设置是否中间状态标志
      this.isIndeterminate = false;
    },
    // 开始分组
    startShuffle() {
      // 选择玩家列表
      this.selectPlayer = this.checkAll ? this.nameList : this.nameChange();
      // 验证玩家数量
      const playerCount = this.selectPlayer.length;
      if (playerCount === 0)
        return showMessage(this, "error", "一个人都不选吗？？？");
      if (playerCount === 1)
        return showMessage(this, "error", "一个人咋玩？？？");
      // 执行洗牌操作
      const shuffleList = shuffle(this.selectPlayer);
      // 将洗牌后的数组分成两组
      const half = Math.ceil(playerCount / 2);
      this.nameGroupOne = shuffleList.slice(0, half);
      this.nameGroupTwo = shuffleList.slice(half);
      // 显示成功消息
      showMessage(this, "success", "分组成功");
    },
    // 添加名字
    async addNameChange() {
      // 校验
      const errorMessage = validateName(this.newName, this.nameList);
      if (errorMessage) {
        return showMessage(this, "error", errorMessage);
      } else {
        try {
          await this.$store.dispatch("user/addName", this.newName); // 触发 action 来添加名字
          this.newName = ""; // 清空输入框
          this.isAdd = false;
          showMessage(this, "success", "添加选手成功");
        } catch (error) {
          showMessage(this, "error", "添加选手失败，请稍后再试");
        }
      }
    },
    // 删除名字
    deleteName(name) {
      this.$store.dispatch("user/removeName", name);
      showMessage(this, "success", "删除选手成功");
      this.clearGroups();
    },
  },
};
</script>

<style scoped>
.app-container_card {
  display: flex;
  justify-content: space-around;
}

.app-container {
  display: flex;
  flex-direction: column;
}

.button-div {
  margin-bottom: 20px;
}

.app-container_card {
  display: flex;
  gap: 20px;
}

.box-card {
  flex: 1;
  text-align: center;
}

.card-content {
  font-size: 12px;
  display: flex;
  flex-wrap: wrap;
  align-items: baseline;
  align-content: flex-start;
  flex-direction: row;
  justify-content: space-between;
}
.text_item {
  width: 50px;
  height: 20px;
  text-align-last: justify;
  font-weight: 700;
}
::v-deep .el-card__body {
  min-height: 150px !important;
  text-align: center;
  overflow: auto;
}
::v-deep .el-checkbox.is-bordered {
  margin: 5px 5px !important;
}
.check-box {
  display: flex;
}
.delete-button {
  font-size: 14px;
  padding: 0;
  padding-bottom: 2.5px;
  padding-left: 5px;
  color: red;
}
::v-deep .el-input--small .el-input__inner {
  width: 110px !important;
}
</style>
